<template>
    <div>
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item><a href="/">商品分类</a></el-breadcrumb-item>
            <el-breadcrumb-item>分类管理</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card>
            <el-alert title="注意:只允许为第三级分类设置相关参数" type="warning" show-icon :closable="false"></el-alert>

            <el-row>
                <el-col>
                    <span>选择商品分类:</span>
                    <el-cascader v-model="selectedId" :options="goodCateList" :props="props"
                        clearable @change="changeCascader" :show-all-levels="false">
                    </el-cascader>
                </el-col>
            </el-row>

            <el-tabs v-model="activeName" @tab-click="handleTabClick">
                <el-tab-pane label="动态参数" name="many">
                    <el-button @click="openAddManyDialog" type="primary" icon="el-icon-edit" :disabled="isCanUseButton" size="medium">添加参数</el-button>

                    <el-table border :data="attrManyList">
                        <el-table-column type="expand">
                            <template slot-scope="{row,$index}">
                                <el-tag :key="index" v-for="(tag,index) in row.attr_vals" closable
                                    :disable-transitions="false" @close="closeTag(row,index)">
                                    {{tag}}
                                </el-tag>

                                <el-input class="input-new-tag" v-if="row.inputVisible" v-model="row.inputValue"
                                    :ref="`saveTagInput${$index}`"
                                    size="small" @keyup.enter.native="$event.target.blur()"
                                    @blur="handleInputConfirm(row)">
                                </el-input>

                                <el-button v-else class="button-new-tag" size="small" @click="showInput(row,$index)">+ 新增</el-button>
                            </template>
                        </el-table-column>

                        <el-table-column type="index" label="序号" align="center" width="50px"></el-table-column>
                        <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="{row,$index}">
                                <el-button type="primary" icon="el-icon-edit" size="mini" @click="openEditAttrDialog(row)">修改</el-button>
                                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteAttr(row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>

                <el-tab-pane label="静态属性" name="only">
                    <el-button type="primary" icon="el-icon-edit" :disabled="isCanUseButton" size="medium" @click="openAddManyDialog">添加参数</el-button>

                    <el-table :data="attrOnlyList" border>
                        <el-table-column type="expand">
                            <template slot-scope="{row,$index}">
                                <el-tag :key="index" v-for="(tag,index) in row.attr_vals" closable
                                    :disable-transitions="false" @close="closeTag(row,index)">
                                    {{tag}}
                                </el-tag>

                                <el-input class="input-new-tag" v-if="row.inputVisible" v-model="row.inputValue"
                                    :ref="`saveTagInput${$index}`"
                                    size="small" @keyup.enter.native="$event.target.blur()"
                                    @blur="handleInputConfirm(row)">
                                </el-input>

                                <el-button v-else class="button-new-tag" size="small" @click="showInput(row,$index)">+ 新增</el-button>
                            </template>
                        </el-table-column>

                        <el-table-column type="index" label="序号" align="center" width="50px"></el-table-column>
                        <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="{row,$index}">
                                <el-button type="primary" icon="el-icon-edit" size="mini" @click="openEditAttrDialog(row)">修改</el-button>
                                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteAttr(row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <!-- 添加参数对话框 -->
        <el-dialog :title="`添加${title}参数`" :visible.sync="manyAttrdialogVisible" @close="closeManyAttrDialog">
            <el-form :model="formForManyAttr" label-width="100px" :rules="formForManyAttrRule" ref="formForManyAttrRef">
                <el-form-item :label="title==='动态'?'动态参数':'静态属性'" prop="attr_name">
                    <el-input v-model="formForManyAttr.attr_name"></el-input>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="manyAttrdialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addAttr">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 修改参数对话框 -->
        <el-dialog :title="`修改${title}参数`" :visible.sync="editAttrdialogVisible" @close="closeManyAttrDialog">
            <el-form :model="formForManyAttr" label-width="100px" :rules="formForManyAttrRule" ref="formForEditAttrRef">
                <el-form-item :label="title==='动态'?'动态参数':'静态属性'" prop="attr_name">
                    <el-input v-model="formForManyAttr.attr_name"></el-input>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="editAttrdialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editAttr">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
  name: 'Params',

  data () {
    return {
      goodCateList: [],
      props: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      selectedId: [],
      activeName: 'many',

      attrManyList: [],
      attrOnlyList: [],

      manyAttrdialogVisible: false,
      formForManyAttr: {
        attr_name: ''
      },
      formForManyAttrRule: {
        attr_name: [
          { required: true, message: '请输入动态参数', trigger: 'blur' }
        ]
      },

      editAttrdialogVisible: false,
      attrId: '' // 属性 ID
    }
  },

  computed: {
    isCanUseButton () {
      return this.selectedId.length !== 3
    },

    title () {
      return this.activeName === 'many' ? '动态' : '静态'
    }
  },

  created () {
    this.getCateList()
  },

  methods: {
    async getCateList () {
      const { data, meta } = await this.$http.goods.getGoodsList({ type: 3 })
      if (meta.status === 200) {
        this.goodCateList = data
      }
    },

    // 当前选中的三级分类的id
    cateId () {
      if (this.selectedId.length === 3) {
        return this.selectedId[2]
      }

      return null
    },

    // 选择商品分类
    changeCascader () {
      this.getAttrList()
    },

    // 获取商品属性列表
    async getAttrList () {
      const { data, meta } = await this.$http.params.getAttrList(+this.cateId(), { params: { sel: this.activeName } })
      if (meta.status === 200) {
        // 将item.attr_vals字符串转换为为数组
        data.forEach(item => {
          // 如果item.attr_vals为空串,进行split(' ')分割是会得到[''],因此要进行校验,在分割
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          // 添加控制button和input属性
          item.inputVisible = false
          item.inputValue = ''
        })

        if (this.selectedId.length !== 3) {
          this.attrManyList = []
          this.attrOnlyList = []
          return
        }

        if (this.activeName === 'many') {
          this.attrManyList = data
        } else {
          this.attrOnlyList = data
        }
      } else {
        this.$message.error('获取商品属性失败')
      }
    },

    // 点击tabs标签,进行tabPane切换
    handleTabClick () {
      this.getAttrList()
    },

    // 打开添加动态参数的对话框
    openAddManyDialog () {
      this.manyAttrdialogVisible = true
    },

    // 关闭添加动态参数的对话框
    closeManyAttrDialog () {
      this.$refs.formForManyAttrRef.resetFields()
    },

    // 添加属性
    addAttr () {
      this.$refs.formForManyAttrRef.validate(async (valid) => {
        if (valid) {
          const { data, meta } = await this.$http.params.addAttr(+this.cateId(), { attr_name: this.formForManyAttr.attr_name, attr_sel: this.activeName })
          if (meta.status === 201) {
            this.$message.success('添加成功')
            this.manyAttrdialogVisible = false
            this.getAttrList()
          } else {
            this.$message.success('添加失败')
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    // 打开修改属性对话框
    openEditAttrDialog (row) {
      this.attrId = row.attr_id
      this.formForManyAttr = { ...row }
      this.editAttrdialogVisible = true
    },

    // 修改属性对话框
    editAttr () {
      this.$refs.formForEditAttrRef.validate(async (valid) => {
        if (valid) {
          const { data, meta } = await this.$http.params.editAttr(+this.cateId(), this.attrId, { attr_name: this.formForManyAttr.attr_name, attr_sel: this.activeName })
          if (meta.status === 200) {
            this.$message.success('修改成功')
            this.editAttrdialogVisible = false
            this.getAttrList()
          } else {
            this.$message.success('修改失败')
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    // 删除属性
    deleteAttr (row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { meta } = await this.$http.params.deleteAttr(+this.cateId(), row.attr_id)
        if (meta.status === 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getAttrList()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 删除Tag标签
    async closeTag (row, index) {
      row.attr_vals.splice(index, 1)

      this.saveAttrVals(row)
    },

    // 将修改和删除的数据保存到数据库中
    async saveAttrVals (row) {
      const { data, meta } = await this.$http.params.addCategories(+this.cateId(), row.attr_id, { attr_vals: row.attr_vals.join(' '), attr_sel: this.activeName, attr_name: row.attr_name })
      console.log('data,meta: ', data, meta)

      if (meta.status === 200) {
        this.$message.success('修改成功')
        row.attr_vals = data.attr_vals.split(' ')
      }
    },

    // 输入Tag
    async handleInputConfirm (row) {
      row.inputVisible = false

      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        return
      }

      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''

      this.saveAttrVals(row)
    },

    // button按钮切换为input
    showInput (row, index) {
      row.inputVisible = true
      // $nextTick 方法的作用，就是当页面上元素被重新渲染之后，才会执行回调函数中的代码
      this.$nextTick(_ => {
        this.$refs[`saveTagInput${index}`].focus()
      })
    }
  }
}
</script>

<style lang="less" scoped>
    .el-row {
        margin: 20px 0;
        span {
            margin-right: 10px;
        }
    }
    .el-button {
        margin-bottom: 20px;
    }
    .el-tag {
        margin-right: 5px;
    }
    .input-new-tag {
        width: 120px;
    }
</style>
